package encrypt.demo;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SM4;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;

import javax.crypto.spec.IvParameterSpec;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Base64;
import java.util.Date;

import static cn.hutool.crypto.Mode.CBC;
import static cn.hutool.crypto.Padding.ZeroPadding;

public class SM4Demo {
    public static void main(String[] args) {
        //初始化
        long begin = new Date().getTime();
        SymmetricCrypto sm4 = new SM4(CBC, ZeroPadding, "0000000000000000".getBytes(),"iviviviviviviviv".getBytes());
        long end = new Date().getTime();
        System.out.println(end-begin);

        //加密
        long en_begin = new Date().getTime();
        byte[] encrypHex = sm4.encrypt("123123");
        for (int i = 0; i < 100; i++) {
            sm4.encrypt("123123123123"+i);
        }
        String cipherTxt = new String(Base64.getEncoder().encode(encrypHex));
        long en_end = new Date().getTime();
        System.out.println(en_end-en_begin);
        System.out.println(cipherTxt);

        //解密
        byte[] newIv = "1234567890123456".getBytes(); // 新的初始化向量
        AlgorithmParameterSpec newParams = new IvParameterSpec(newIv);
        sm4.setParams(newParams); // 设置新的参数
        long de_begin = new Date().getTime();
        String decryptStr = sm4.decryptStr(Base64.getDecoder().decode(cipherTxt));
        long de_end = new Date().getTime();
        System.out.println(de_end-de_begin);
        System.out.println(new String(decryptStr));
    }
}
